from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from .. import db
from ..models import Field, Sensor, Task, Decision, SensorData, User, Role
from ..services.decision_service import DecisionService
from datetime import datetime
from ..database import save_db_data

bp = Blueprint('api', __name__)
decision_service = DecisionService()

@bp.route('/fields', methods=['GET'])
@login_required
def get_fields():
    """获取所有农田"""
    return jsonify([field.to_dict() for field in db.fields])

@bp.route('/fields', methods=['POST'])
@login_required
def create_field():
    """创建新农田"""
    data = request.get_json()
    
    if not data or not data.get('name'):
        return jsonify({'error': '缺少必要参数'}), 400
    
    field = Field(
        name=data['name'],
        area=data.get('area', 0),
        current_crop=data.get('current_crop'),
        boundary=data.get('boundary', [])
    ).save()
    
    save_db_data()
    return jsonify(field.to_dict())

@bp.route('/fields/<int:field_id>/sensors')
@login_required
def get_field_sensors(field_id):
    sensors = Sensor.find_by_field(field_id)
    return jsonify([sensor.to_dict() for sensor in sensors])

@bp.route('/decisions/<type>/<int:field_id>')
@login_required
def get_decision(type, field_id):
    if type not in ['irrigation', 'fertilizer', 'pesticide']:
        return jsonify({'error': '无效的决策类型'}), 400
    
    # 生成决策
    analysis_result, recommendation = decision_service.generate_decision(type, field_id)
    
    # 保存决策
    decision = Decision(
        field_id=field_id,
        decision_type=type,
        analysis_result=analysis_result,
        recommendation=recommendation
    ).save()
    
    return jsonify(decision.to_dict())

@bp.route('/fields/<int:field_id>/decisions')
@login_required
def get_field_decisions(field_id):
    decision_type = request.args.get('type')
    limit = int(request.args.get('limit', 10))
    
    decisions = Decision.find_by_field(field_id, decision_type, limit)
    return jsonify([d.to_dict() for d in decisions])

@bp.route('/tasks', methods=['POST'])
@login_required
def create_task():
    data = request.get_json()
    task = Task(
        title=data['title'],
        description=data.get('description'),
        task_type=data['task_type'],
        priority=data.get('priority', 3),
        field_id=data['field_id'],
        created_by=str(current_user._id),
        assigned_to=data.get('assigned_to'),
        due_date=datetime.fromisoformat(data['due_date']) if data.get('due_date') else None,
        decision_id=data.get('decision_id')
    ).save()
    return jsonify({"message": "任务创建成功", "id": str(task._id)})

@bp.route('/devices', methods=['GET'])
@login_required
def get_devices():
    """获取所有设备"""
    return jsonify([device.to_dict() for device in db.sensors])

@bp.route('/devices', methods=['POST'])
@login_required
def create_device():
    """创建新设备"""
    data = request.get_json()
    
    if not data or not all(k in data for k in ('name', 'device_type', 'field_id')):
        return jsonify({'error': '缺少必要参数'}), 400
    
    device = Sensor(
        name=data['name'],
        device_type=data['device_type'],
        field_id=data['field_id']
    ).save()
    
    save_db_data()
    return jsonify(device.to_dict())

@bp.route('/devices/<int:device_id>/data', methods=['GET'])
@login_required
def get_device_data(device_id):
    """获取设备数据"""
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    limit = request.args.get('limit', 100, type=int)
    
    data = SensorData.find_by_sensor(device_id, start_time, end_time, limit)
    return jsonify([d.to_dict() for d in data])

@bp.route('/tasks/<task_id>/status', methods=['PUT'])
@login_required
def update_task_status(task_id):
    data = request.get_json()
    task = Task.find_by_id(task_id)
    if not task:
        return jsonify({'error': '任务不存在'}), 404
        
    task.status = data['status']
    if data['status'] == 'completed':
        task.completed_at = datetime.utcnow()
    task.save()
    return jsonify({"message": "任务状态更新成功"})

@bp.route('/sensors/<sensor_id>/data', methods=['GET'])
@login_required
def get_sensor_data(sensor_id):
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    limit = int(request.args.get('limit', 100))
    
    data = SensorData.find_by_sensor(
        sensor_id,
        start_time=datetime.fromisoformat(start_time) if start_time else None,
        end_time=datetime.fromisoformat(end_time) if end_time else None,
        limit=limit
    )
    return jsonify([d.to_dict() for d in data])

@bp.route('/users', methods=['POST'])
@login_required
def create_user():
    """创建新用户"""
    data = request.get_json()
    
    if not data or not all(k in data for k in ('username', 'email', 'password', 'role')):
        return jsonify({'error': '缺少必要参数'}), 400
    
    if User.find_by_username(data['username']):
        return jsonify({'error': '用户名已存在'}), 400
    
    user = User.create_user(
        username=data['username'],
        email=data['email'],
        password=data['password'],
        role=data['role']
    )
    
    save_db_data()
    return jsonify(user.to_dict())

@bp.route('/users/<int:user_id>', methods=['PUT'])
@login_required
def update_user(user_id):
    """更新用户信息"""
    user = User.find_by_id(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    data = request.get_json()
    if user.update(data):
        save_db_data()
        return jsonify(user.to_dict())
    return jsonify({'error': '更新失败'}), 400

@bp.route('/users/<int:user_id>', methods=['DELETE'])
@login_required
def delete_user(user_id):
    """删除用户"""
    user = User.find_by_id(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    if user.delete():
        save_db_data()
        return jsonify({'message': '删除成功'})
    return jsonify({'error': '删除失败'}), 400

@bp.route('/roles/<role_name>/permissions', methods=['PUT'])
@login_required
def update_role_permissions(role_name):
    """更新角色权限"""
    role = Role.find_by_name(role_name)
    if not role:
        return jsonify({'error': '角色不存在'}), 404
    
    data = request.get_json()
    permission = data.get('permission')
    action = data.get('action')
    
    if not permission or action not in ['add', 'remove']:
        return jsonify({'error': '无效的请求'}), 400
    
    if action == 'add':
        if permission not in role.permissions:
            role.permissions.append(permission)
    else:
        if permission in role.permissions:
            role.permissions.remove(permission)
    
    role.save()
    save_db_data()
    return jsonify(role.to_dict())

@bp.route('/fields/<int:field_id>', methods=['GET'])
@login_required
def get_field(field_id):
    """获取农田信息"""
    field = Field.find_by_id(field_id)
    if not field:
        return jsonify({'error': '农田不存在'}), 404
    return jsonify(field.to_dict())

@bp.route('/fields/<int:field_id>', methods=['PUT'])
@login_required
def update_field(field_id):
    """更新农田信息"""
    field = Field.find_by_id(field_id)
    if not field:
        return jsonify({'error': '农田不存在'}), 404
    
    data = request.get_json()
    if field.update(data):
        save_db_data()
        return jsonify(field.to_dict())
    return jsonify({'error': '更新失败'}), 400

@bp.route('/fields/<int:field_id>', methods=['DELETE'])
@login_required
def delete_field(field_id):
    """删除农田"""
    field = Field.find_by_id(field_id)
    if not field:
        return jsonify({'error': '农田不存在'}), 404
    
    if field.delete():
        save_db_data()
        return jsonify({'message': '删除成功'})
    return jsonify({'error': '删除失败'}), 400 